package com.lyhlmj.oop_client.Style.Buttons.WaitFrameButton;

import com.lyhlmj.oop_client.ClientOperation.ClientUtil.Client;
import com.lyhlmj.oop_client.Frames.PlayFrame.PlayFrame;
import com.lyhlmj.oop_client.Style.Buttons.GeneralButton;
import com.lyhlmj.oop_client.Threads.GetPlayStatusTask;
import com.lyhlmj.oop_client.Utils.Request;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;

public class ReadyButton extends GeneralButton {
    private Client client = Client.client;
    private Window owner;

    public ReadyButton(String str, Window owner) {
        super(str);
        this.owner = owner;
    }

    public void doReady() {
        //创建获取游戏状态的线程
        client.getPlayStatusTask = new GetPlayStatusTask(owner);
        GetPlayStatusTask getPlayStatusTask = client.getPlayStatusTask;
        getPlayStatusTask.start();

        // 设置准备按钮只可以单击一次
        this.setEnabled(false);

        //  修改状态为匹配态
        JSONObject jsonReq = Request.getJsonObject("ready", "username", client.getUsername());
        client.send(jsonReq, new Client.Callback() {
            @Override
            public void onResult(int status, String reason, JSONObject data) {  //回调函数
                if (status == 0) {
                    JOptionPane.showMessageDialog(owner, reason);
                }

                //匹配成功后提示用户，并自动跳转到游戏界面
                while (getPlayStatusTask.getTheStatus() == null || !getPlayStatusTask.getTheStatus().equals("1")) {
                    try {
                        Thread.sleep(1000);  //进程休息1s
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //如果后端一直没有创建对局(匹配不成功)，则阻塞在此
                    // TODO 添加用户等待时间的计时器
                }

                client.setChatRoomId(data.optString("chatRoomId", ""));
                JOptionPane.showMessageDialog(owner, "匹配成功！开始对局！");
                System.out.println("用户" + client.getUsername() + "准备开始对局！");

                owner.dispose(); //销毁准备框架
                PlayFrame.initial();  //进入五子棋对局框架
            }
        });
    }
}
